const co = require('co')
const {
	select,
	selectOne,
	insert,
	insertBatch,
	update,
	executeSQL,
	remove,
} = require('../db-mysql')

const table = 'tb_parameter_template'
const fields = [
	'id',
	'name',
	'description',
	'template',
	'project_id',
	'module_api_id'
]

module.exports = {
	listTemplate() {
		let SQL = 'SELECT tpt.id, tpt.name, tpt.description, tpt.template, tpt.project_id, tpt.module_api_id, tp.name AS project_name FROM tb_parameter_template tpt'
		SQL += ' LEFT JOIN tb_project tp ON tpt.project_id = tp.id'
		SQL += ' ORDER BY tpt.id DESC'
		return executeSQL(SQL)
	},

	addTemplate(params) {
		let values = []
		let addFields = fields.filter((val, idx) => {
			if (val == 'id')
				return false
			else
				values.push(`'${params[val] || ''}'`)
			return true
		});
		return insert({
			table,
			fields: addFields,
			values,
		})
	},

	updateTemplate(params) {
		return update({
			table,
			updates: [`name = '${params.name}'`, `description = '${params.description}'`, `template = '${params.template}'`],
			where: [`id = '${params.id}'`],
		})
	},

	removeTemplateById(templateId) {
		return remove({
			table,
			where: [`id = ${templateId}`]
		})
	},

	checkTemplateByModuleApiId(module_api_id) {
		return selectOne({
			table,
			fields,
			where: [`module_api_id = '${module_api_id}'`],
		})
	},
}